﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;

/// <summary>
/// 绑定在背包方格上
/// 右键吃药就是在这里
/// 说明：预制体Slot上，Button脚本上，有个Navigation，默认是Automatic，这样会导致一种情况，在点击一下背包格后，按方向键控制Player行走，会顺带方格一起移动。改成None就没事了。
/// </summary>
public class Slot : MonoBehaviour,IPointerClickHandler {

	private Stack<Item> items;
	public Stack<Item> Items {
		get {
			return items;
		}
		set {
			items = value;
		}
	}

	// 栈

	public Text stackTxt;

	public Sprite slotEmpty;
	public Sprite slotHightlight;



	public bool IsEmpty{
		get{ return items.Count == 0; }
	}

	public bool IsAvailable{
		get{ return CurrentItem.maxSize > items.Count; }
	}

	public Item CurrentItem{
		get{ return items.Peek ();}
	}



	// Use this for initialization
	void Start () {
		items = new Stack<Item> ();
		RectTransform slotRect = GetComponent<RectTransform> ();
		RectTransform txtRect = stackTxt.GetComponent<RectTransform> ();

		int txtScleFactor = (int)(slotRect.sizeDelta.x * 0.60);
		stackTxt.resizeTextMaxSize = txtScleFactor;
		stackTxt.resizeTextMinSize = txtScleFactor;

		txtRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, slotRect.sizeDelta.x);
		txtRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, slotRect.sizeDelta.y);
	}
	
	// Update is called once per frame
	void Update () {
	
	}


	public void AddItem(Item item){
		
		items.Push (item);

		if (items.Count > 1) {
			stackTxt.text = items.Count.ToString ();
		}
		ChangeSprite (item.spriteNeutral, item.spriteHighlighted);
	}

	public void AddItems(Stack<Item> items){
		
		this.items = new Stack<Item> (items);      //todo ???

		stackTxt.text = items.Count > 1 ? items.Count.ToString () : string.Empty;
		 
		ChangeSprite (CurrentItem.spriteNeutral, CurrentItem.spriteHighlighted);
	}


	private void ChangeSprite(Sprite neutral,Sprite hightlight){
		GetComponent<Image> ().sprite = neutral;

		SpriteState st = new SpriteState ();
		st.highlightedSprite = hightlight;
		st.pressedSprite = neutral;

		GetComponent<Button> ().spriteState = st;
	}

	private void UseItem(){
		if (!IsEmpty) {
			items.Pop ().Use ();

			stackTxt.text = items.Count > 1 ? items.Count.ToString () : string.Empty;

			if (IsEmpty) {
				ChangeSprite (slotEmpty, slotHightlight);
				Inventory.EmptySlots++;
			}
		}
	}


	public void ClearSlot(){
		items.Clear ();
		ChangeSprite (slotEmpty, slotHightlight);
		stackTxt.text = string.Empty;
	}

	public void OnPointerClick(PointerEventData eventData){
		if (eventData.button == PointerEventData.InputButton.Right) {
			UseItem ();
		}		
	}
}
